<?php
/**
 * 首页导航控制器
 * User: ws
 * Date: 2018/9/27
 * Time: 14:56
 */

namespace app\admin\controller;
use app\admin\model\Navigation as NModel;
class Navig  extends Init
{
    function index(){
        if ($this->request->isAjax()) {
            $list = NModel::order('sort desc ,navigation_id desc')->paginate(input('limit'))->toArray();
            $url = config('aliyun_oss.url');
            foreach ($list['data'] as $key=>$itme){
                $list['data'][$key]['img'] = str_replace("/navig",$url."navig",$itme['img']);
            }
            return json($result = ['code'=>0,'msg'=>'获取成功','data'=>$list['data'],'count'=>$list['total']]);
        }
        return view('list');
    }

    function add(){
        if(request()->isPost()){
            $data = $this->request->post();
            if($data['type']==0){
                unset($data['url']);
            }elseif ($data['type']==1){
                if(empty($data['url'])){
                    return json(array('code'=>0,'msg'=>'添加失败，url不能为空'));
                }
            }
            if(empty($data['img'])){
                return json(array('code'=>0,'msg'=>'添加失败，请上传图片'));
            }

            if (!NModel::create($data)) {
                return json(array('code'=>0,'msg'=>'添加失败'));
            }
            return json(array('code'=>200,'msg'=>'添加成功'));
        }
        return view('add');
    }


    function edit(){
        if(request()->isPost()){
            $data = $this->request->post();
            if($data['type']==0){
               $data['url'] = '';
            }elseif ($data['type']==1){
                if(empty($data['url'])){
                    return json(array('code'=>0,'msg'=>'添加失败，url不能为空'));
                }
            }
            if(empty($data['img']))
                unset($data['img']);
            if (!NModel::update($data)) {
                return json(array('code'=>0,'msg'=>'修改失败'));
            }
            return json(array('code'=>200,'msg'=>'修改成功'));
        }

        $list = NModel::where('navigation_id', input('id'))->find()->toArray();
        $url = config('aliyun_oss.url');
        $list['img'] = str_replace("/navig",$url."navig",$list['img']);
        return view('edit',['list'=>$list]);
    }

    function del(){
        if (!NModel::destroy(['navigation_id' => input('param.id')])) {
            return json(array('code'=>0,'msg'=>'删除失败'));
        }
        return json(array('code'=>200,'msg'=>'删除成功'));
    }
}